package com.dcivision.dms.core;

import java.sql.Connection;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dcivision.dms.bean.DmsArchive;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRetentionSetup;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsRetentionSetupDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.Utility;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.dao.UserRecordDAObject;

public class DmsProfileJob implements Job {
	protected Log log = LogFactory.getLog(this.getClass().getName());
	
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		log.info("start retention period");
		JobDataMap dataMap = arg0.getJobDetail().getJobDataMap();
		List retentionList = new ArrayList();
		Connection conn = null;
		SessionContainer sessionContainer = null;
		
		try {
      sessionContainer = new SessionContainer();
      conn = DataSourceFactory.getConnection();
            
      // lee 06/12/06 EIP-440 / update database need update_id(userRecordID).
      UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionContainer, conn);
      sessionContainer.setUserRecord((UserRecord)userRecordDAO.getObjectByID(new Integer("0")));
      // lee 06/12/06 EIP-440 
      
      // lee 06/12/06 EIP-1405 Administator has all permission
      sessionContainer.setByPassPermission(true);
      sessionContainer.setUserIPAddress("127.0.0.1");
      
      DmsRetentionSetupDAObject retentionDAO = new DmsRetentionSetupDAObject(sessionContainer,conn);      
      retentionList = retentionDAO.getFullList();
      
      if (!Utility.isEmpty(retentionList)){
      	for (int i =0;i < retentionList.size(); i++){
      		DmsRetentionSetup dmsRetentionSetup = (DmsRetentionSetup)retentionList.get(i);
      		if ("D".equals(dmsRetentionSetup.getActionName())){
      			this.delete(sessionContainer,conn,dmsRetentionSetup);
      		} else if ("A".equals(dmsRetentionSetup.getActionName())){
      			if (!Utility.isEmpty(dataMap.getString("viewPath"))){
      				this.archive(sessionContainer,conn,dmsRetentionSetup,dataMap.getString("viewPath"));
      			}
      		}
      	}
      }
      conn.commit(); // EIP-1405 07/01/04 LEE ADD
    } catch (Exception e) {
      try {conn.rollback();}catch (Exception ignore) {}
      log.error(e, e);
    } finally {
      try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
    }		
	}
	
	private void delete(SessionContainer sessionContainer, Connection conn, DmsRetentionSetup dmsRetentionSetup) throws ApplicationException {
		Integer udfIndexID = dmsRetentionSetup.getObjectID();
		Timestamp period = this.getPeriod(dmsRetentionSetup);
		if (!Utility.isEmpty(period)) {
  		DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer,conn);
      // Personal documents will be selected to list too. EIP-1448 07/01/15 LEE
  		List result = dmsDocumentDAO.getDocumentListByUdfIndexIDCreateDate(udfIndexID, period, false);
      //List result = dmsDocumentDAO.getDocumentListByUdfIndexIDCreateDate(udfIndexID, period);
      
      // Replace delete logic with deleteListData method. EIP-1405 07/01/04 LEE 
      this.deleteListData(sessionContainer, conn, result);
    }
	}
	
	private void archive(SessionContainer sessionContainer, Connection conn, DmsRetentionSetup dmsRetentionSetup,String offlineViewPath ) throws ApplicationException {
		Integer udfIndexID = dmsRetentionSetup.getObjectID();
		Timestamp period = this.getPeriod(dmsRetentionSetup);
		
		DmsArchiveManager dmsArchiveManager = new DmsArchiveManager(sessionContainer,conn);
		//get DmsArchive
		Timestamp curTime = Utility.getCurrentTimestamp();
		DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
		String archiveName = "Archive-admin-" + dateFormat.format(curTime);
		
		DmsArchive dmsArchive = new DmsArchive();
		dmsArchive.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
		dmsArchive.setArchiveName(archiveName);
		dmsArchive.setCreatorID(new Integer(0));
		dmsArchive.setUpdaterID(new Integer(0));
//		dmsArchive.setRootID(new Integer(1));
		dmsArchive.setArchiveType(DmsArchive.ARCHIVE_TYPE);
    
//  get dms archive list
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer,conn);
    List result = dmsDocumentDAO.getDocumentListByUdfIndexIDCreateDate(udfIndexID,period);
    
    // Replace archive logic with code below. EIP-1405 07/01/04 LEE 
    try {
      DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
      
      String[] arrDocumentID = new String[result.size()];
      for (int i=0; i<result.size(); i++) {
        arrDocumentID[i] = ((DmsDocument)result.get(i)).getID().toString();
      }
      
      arrDocumentID = docValidateManager.validatorFilterDocID(arrDocumentID);
      
      DmsValidation validation = dmsArchiveManager.validateArchiveAction(dmsArchive, arrDocumentID, null, null, null, true);
      if (validation.isSuccess()) {
        dmsArchiveManager.archiveDocument(dmsArchive, validation, arrDocumentID, null, offlineViewPath, null, null);
      }
    }catch (Exception ex) {
      log.error(ex, ex);
    }
    /*
    if (!Utility.isEmpty(result)){
    	dmsArchiveManager.startArchive(result,dmsArchive,offlineViewPath);
    	log.info("Archive Document success");
    }		
    */
	}
	
	private Timestamp getPeriod(DmsRetentionSetup dmsRetentionSetup){
		Timestamp curTime = Utility.getCurrentTimestamp();
		Integer year = dmsRetentionSetup.getPeriodYear();
		Integer month = dmsRetentionSetup.getPeriodMonth();
		Integer day = dmsRetentionSetup.getPeriodDay();
		
		if (Utility.isEmpty(year) && Utility.isEmpty(month) && Utility.isEmpty(day)){
			return null;
		}
		
		if (!Utility.isEmpty(year)){
			curTime = Utility.addYear(curTime,-year.intValue());
		}
		
		if (!Utility.isEmpty(month)){
			curTime = Utility.addMonth(curTime,-month.intValue());
		}
		
		if (!Utility.isEmpty(day)){
			curTime = Utility.addDay(curTime,-day.intValue());
		}
		
		return curTime;
	}
  
  /**
   * Delete dms document with gived list. EIP-1405 07/01/04 LEE 
   * @param sessionContainer
   * @param conn
   * @param listDmsDocument
   * @throws ApplicationException
   */
  private void deleteListData(SessionContainer sessionContainer, Connection conn, List listDmsDocument) throws ApplicationException {
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    
    //step 1: loop and validate tree node, add id to lstIdHasRight/lstIdMisRight/lstIdBeLocked
    for (int n=0; n<listDmsDocument.size(); n++) {
      DmsDocument sourceDocument = (DmsDocument)listDmsDocument.get(n);
      try {
        DmsValidation validation = docValidateManager.validateDeleteAction(sourceDocument, false);
        //step 2.1: delete action
        docOperationManager.deleteDocument(sourceDocument, validation);
        
        if (!validation.isSuccess()) {
          log.info("Profile Schedule Job: "+sourceDocument.getDocumentName()+"("+sourceDocument.getID()+") deleted failure.");
        }
      }catch (Exception ex) {
        log.error(ex, ex);
      }
    }
    docValidateManager.release();
    docOperationManager.release();
  }
  
  
	
}
